package com.i3.office.common.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 日期时间处理，适配达梦数据库
 * @author:张三石
 * @since:2023年3月30日 下午5:09:37
 */
@Component
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> implements ApplicationContextAware {
	public LocalDateTimeTypeHandler() {
	}

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
		if (parameter == null) {
			ps.setTimestamp(i, null);
			return;
		}
		ps.setTimestamp(i, Timestamp.valueOf(parameter));

	}

	@Override
	public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
		Timestamp timestamp = rs.getTimestamp(columnName);
		if (timestamp == null) {
			return null;
		}
		return timestamp.toLocalDateTime();
	}

	@Override
	public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		Timestamp timestamp = rs.getTimestamp(columnIndex);
		if (timestamp == null) {
			return null;
		}
		return timestamp.toLocalDateTime();
	}

	@Override
	public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		Timestamp timestamp = cs.getTimestamp(columnIndex);
		if (timestamp == null) {
			return null;
		}
		return timestamp.toLocalDateTime();
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

		// 从spring容器获取sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
		// 获取typeHandler注册器
		TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();
		// 注册typeHandler
		typeHandlerRegistry.register(LocalDateTime.class, LocalDateTimeTypeHandler.class);

	}
}
